package com.we.es.query;

import java.util.ArrayList;
import java.util.List;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;

import com.uxuexi.core.common.util.Util;
import com.we.es.entity.EsIndexEntity;
import com.we.es.support.IndexHelper;

/**
 * 用于处理查询结果
 *
 * @author   朱晓川
 * @Date	 Aug 12, 2014 	 
 */
public abstract class AbstractResponseHandler {

	protected SearchResponse response;

	protected SearchResult result;

	protected Class<?> entityClazz;

	/**
	 * 处理服务器的响应
	 */
	public AbstractResponseHandler(SearchResponse response, Class<?> entityClazz) {
		this.response = response;
		this.entityClazz = entityClazz;
	}

	/**
	 * 处理逻辑，模板方法
	 */
	public final SearchResult transfer() {
		if (Util.isEmpty(response))
			return null;

		//检查是否为空
		checkResult();

		setBasicInfo();

		result = this.handleResponse(); //执行自己的处理逻辑 

		return result;
	}

	protected abstract SearchResult handleResponse();

	/**
	 * 处理基本信息
	 *
	 * @param entityClass 数据实体类型
	 */
	protected void setBasicInfo() {
		//要返回的entity结果集
		List<EsIndexEntity> data = new ArrayList<EsIndexEntity>();

		//查询结果集
		SearchHits hits = response.getHits();

		long total = hits.getTotalHits();
		result.setTotal(total);
		result.setTime(response.getTook().millis());
		try {
			for (SearchHit hit : hits) {
				Object entity = entityClazz.newInstance();
				IndexHelper.setEntityValueFromDoc(entity, hit);
				data.add((EsIndexEntity) entityClazz.cast(entity));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		result.setData(data);

	}

	private void checkResult() {
		if (Util.isEmpty(result)) {
			result = new SearchResult();
		}
	}
}